import serviceApi from 'api/service'

const state = {
  service_list: [],
  service_detail: null
}
const getters = {
  service_list: state => state.service_list,
  service_detail: state => state.service_detail
}

const actions = {
  service_list ({commit, state}, params) {
    serviceApi.goodsList(params).then((json) => {
      commit('SERVICE_LIST', json)
    })
  },
  service_detail ({ commit, state }, params) {
    return serviceApi.serviceDetail(params)
    .then((json) => {
      function detailFormatData (json) {
        let mapList = json.data.attributeMappingList
        let selectItems = []
        let selectItem = []
        for (var j = 0; j < mapList.length; j++) {
          if (mapList[j].parentAttrCode === '0') {
            selectItems.push(mapList[j])
          } else {
            selectItem.push(mapList[j])
          }
        }
        for (var i = 0; i < selectItems.length; i++) {
          let select = []
          for (var a = 0; a < selectItem.length; a++) {
            if (selectItems[i].attrCode === selectItem[a].parentAttrCode) {
              select.push(selectItem[a])
            }
          }
          selectItems[i].selects = select
          selectItems[i].sort = select[0].attrCode // 设单选初始值，第一个
        }
        json.data.attributeMappingListUse = selectItems
        return json
      }
      detailFormatData(json)
      commit('SERVICE_DETAIL', {data: json.data})
    })
    .catch(() => {})
  }
}

const mutations = {
  SERVICE_LIST (state, data) {
    state.service_list = data.data ? data.data : []
  },
  SERVICE_DETAIL (state, data) {
    state.service_detail = data.data
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
